package cn.dakaqi.open.api.v1;

import cn.dakaqi.annotation.Login;
import cn.dakaqi.entities.*;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.services.*;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.util.ConfigUtil;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import cn.dakaqi.utils.redis.RedisClientTemplate;
import cn.dakaqi.vo.db.OrgTestVo;
import cn.dakaqi.vo.response.DKQPage;
import cn.dakaqi.vo.response.IndexDataVO;
import cn.dakaqi.vo.response.ListDataResponseVo;
import cn.dakaqi.vo.response.SearchResultVO;
import com.wordnik.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springside.modules.web.MediaTypes;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chunyang on 2016/4/21.
 */
@RestController
@RequestMapping(value = "/api/v1/index")
@Api(value = "首页数据API")
@Slf4j
public class IndexRestController
{
    @Autowired
    GroupVolunteerService groupVolunteerService;
    @Autowired
    ActivityService activityService;
    @Autowired
    GroupService groupService;
    @Autowired
    SysTopicService sysTopicService;
    @Autowired
    GroupRecruitService groupRecruitService;
    @Autowired
    ActivityRecruitService activityRecruitService;
    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    IndexDataService indexDataService;

    @Resource
    ConfigUtil configUtil;

    Activity topActivity = null;
    GroupRecruit topGroupRecuit = null;
    ActivityRecruit topActivityRecruit = null;

    @RequestMapping(value = "/{city}/{memberCode}/{pageNumber}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> memberCode(@PathVariable("city") String city,@PathVariable("memberCode") String memberCode, @PathVariable("pageNumber") int pageNumber)
    {
        JsonResult jsonResult = new JsonResult();
        Map<String, Object> resultMap = new HashMap<String, Object>();

        try
        {
/*                if (null != memberCode && !"null".equals(memberCode.trim().toLowerCase()) && StringUtils.isNotBlank(memberCode))
                {
//                    //根据条件，找出当前用户所喜好的标签
//                    Volunteer volunteer = volunteerService.findByMemberCode(memberCode);
//                    String cityStr;
//                    if("default".equalsIgnoreCase(city)){
//                        cityStr = volunteer.getCity();
//                    }else{
//                        cityStr = city;
//                    }
//                    if (null != volunteer)
//                    {
//                        Page<IndexData> dataPage = indexDataService.findAll(cityStr, volunteer.getJob(), volunteer.getServiceField(), volunteer.getSkill(), pageNumber);
//
//                        resultMap.put("list", dataPage.getContent());
//                        resultMap.put("page", new DKQPage(dataPage));
//                        jsonResult.setCode(JsonResult.CODE_SUCCESS);
//                        jsonResult.setMessage("查询成功");
//                        jsonResult.setData(resultMap);
//                    }
                }
                else
                {
                    Page<IndexData> dataPage = indexDataService.findDefault(pageNumber);
                    resultMap.put("list", dataPage.getContent());
                    resultMap.put("page", new DKQPage(dataPage));
                    jsonResult.setCode(JsonResult.CODE_SUCCESS);
                    jsonResult.setMessage("查询成功");
                    jsonResult.setData(resultMap);
                }*/


            Page<IndexData> dataPage = indexDataService.findDefault(pageNumber);
            List<IndexDataVO> list = new ArrayList<IndexDataVO>();
            for(IndexData indexData:dataPage.getContent())
            {
                list.add(IndexDataVO.buildVO(indexData));
            }

            if (null != memberCode && !"null".equals(memberCode.trim().toLowerCase()) && StringUtils.isNotBlank(memberCode) && pageNumber == 1)
            {
                int index = 0;
                //获取头条信息
                getTop(memberCode);
                if(null != topActivity)
                {
                    if(null != list)
                    {
                        IndexDataVO indexData = packData(1, topActivity);
                        district(list,indexData);
                        list.add(index,indexData);
                    }
                }
                else if(null != topActivityRecruit)
                {
                    IndexDataVO indexData =packData(3,topActivityRecruit);
                    district(list,indexData);
                    list.add(index,indexData);
                }
                else if(null != topGroupRecuit)
                {
                    IndexDataVO indexData = packData(2,topGroupRecuit);
                    district(list,indexData);
                    list.add(index,indexData);
                }
            }

            resultMap.put("list", list);
            resultMap.put("page", new DKQPage(dataPage));
            jsonResult.setCode(JsonResult.CODE_SUCCESS);
            jsonResult.setMessage("查询成功");
            jsonResult.setData(resultMap);

        }catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }

        return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
    }

    private List<IndexDataVO> district(List<IndexDataVO> list,IndexDataVO indexData)
    {
        int index = 0;

        for(int i=0;i<list.size();i++)
        {
            IndexDataVO temp = list.get(i);
            if(temp.getTitle().equals(indexData.getTitle()))
            {
                index = i;
                break;
            }
        }
        list.remove(index);
        return list;
    }
    private void getTop(String memberCode)
    {
        String lastType = "";
        Object lastObject = null;
        Date lastDate = null;

        //检查当前用户是否有效
        Volunteer volunteer = volunteerService.findByMemberCode(memberCode);
        if(null == volunteer)
            return;
        //检查当前用户所参加的社团
        Page<GroupVolunteer> groupVolunteers = this.groupVolunteerService.queryMemberCode(volunteer.getMemberCode(), DKQConstant.APPLY_STATUS_OK,1);
        if(null == groupVolunteers || groupVolunteers.getContent() == null || groupVolunteers.getContent().size() == 0)
            return;

        //检查当前用户是否发布过当天的活动
        Page<Activity> data = activityService.findByCreateUser(volunteer.getId(), 1);
        if(null != data && data.getContent() != null && data.getContent().size()>0)
        {
            Activity activity = data.getContent().get(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String today = sdf.format(new Date());
            String createDay = sdf.format(activity.getCreateTime());
            if(today.equals(createDay))
            {
                //若当前活动对外招募，则查询当前活动的招募信息
                ActivityRecruit ar = activityRecruitService.findByActivityCode(activity.getActivityCode());
                if(null != ar)
                {
                    lastDate = ar.getCreateTime();
                    lastType = "topActivityRecruit";
                    lastObject = ar;
                }
                else
                {
                    lastDate = activity.getCreateTime();
                    lastType = "topActivity";
                    lastObject = activity;
                }
            }
        }
        //检查当前用户是否发布过当天的社团招募
        Page<GroupRecruit> groupRecruits = groupRecruitService.findByVolunteer(volunteer.getMemberCode(),1);
        if(null != groupRecruits && groupRecruits.getContent() != null && groupRecruits.getContent().size()>0)
        {
            GroupRecruit groupRecruit = groupRecruits.getContent().get(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String today = sdf.format(new Date());
            String createDay = sdf.format(groupRecruit.getCreateTime());
            if(today.equals(createDay))
            {
                if(null == lastDate)
                {
                    lastDate = groupRecruit.getCreateTime();
                    lastType = "topGroupRecuit";
                    lastObject = groupRecruit;
                }
                if(null != lastDate && lastDate.before(groupRecruit.getCreateTime()))
                {
                    lastDate = groupRecruit.getCreateTime();
                    lastType = "topGroupRecuit";
                    lastObject = groupRecruit;
                }
            }
        }

        //检查当前用户所参加的社团当天有没有活动或招募
        //社团今天有没有发布新的活动
        for(GroupVolunteer gv:groupVolunteers.getContent())
        {
            Page<Activity> actData = this.activityService.findByGroup(gv.getId(),1);
            if(null != actData && actData.getContent()!= null && actData.getContent().size()>0)
            {
                Activity activity = actData.getContent().get(0);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String today = sdf.format(new Date());
                String createDay = sdf.format(activity.getCreateTime());
                if(today.equals(createDay))
                {
                    if(null == lastDate)
                    {
                        lastDate = activity.getCreateTime();
                        lastType = "topActivity";
                        lastObject = activity;
                    }
                    if(null != lastDate && lastDate.before(activity.getCreateTime()))
                    {
                        lastDate = activity.getCreateTime();
                        lastType = "topActivity";
                        lastObject = activity;
                    }
                    break;
                }
            }
        }
        //社团今天有没有发布招募
        for(GroupVolunteer gv:groupVolunteers.getContent())
        {
            Page<GroupRecruit> datas = this.groupRecruitService.findByGroupCode(gv.getGroup().getGroupCode(), 1);
            if(null != datas && datas.getContent() != null && datas.getContent().size()>0)
            {
                GroupRecruit groupRecruit = datas.getContent().get(0);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String today = sdf.format(new Date());
                String createDay = sdf.format(groupRecruit.getCreateTime());
                if(today.equals(createDay))
                {
                    if(null == lastDate)
                    {
                        lastDate = groupRecruit.getCreateTime();
                        lastType = "topGroupRecuit";
                        lastObject = groupRecruit;
                    }
                    if(null != lastDate && lastDate.before(groupRecruit.getCreateTime()))
                    {
                        lastDate = groupRecruit.getCreateTime();
                        lastType = "topGroupRecuit";
                        lastObject = groupRecruit;
                    }
                }
            }
        }
        if(lastType.equals("topGroupRecuit"))
        {
            topGroupRecuit = (GroupRecruit)lastObject;
        }
        else if(lastType.equals("topActivity"))
        {
            topActivity = (Activity)lastObject;
        }
        else if(lastType.equals("topActivityRecruit"))
        {
            topActivityRecruit = (ActivityRecruit)lastObject;
        }
    }
    private IndexDataVO packData(int type,Object object)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        IndexDataVO indexDataVO = new IndexDataVO();
        if(type == 1)
        {
            Activity activity = (Activity)object;
            indexDataVO.setId(-1L);
            indexDataVO.setType("ActivityRecruit");
            indexDataVO.setCode(activity.getActivityCode());
            indexDataVO.setObjectId(activity.getId());
            indexDataVO.setTitle(activity.getName());
            indexDataVO.setCreateTime(activity.getCreateTime());
            indexDataVO.setImg("http://img.dakaqi.cn/old4.jpg");
            indexDataVO.setParticipants(activity.getApplys());
            indexDataVO.setBrowses(activity.getBrowses());
            indexDataVO.setOrgName(activity.getGroup().getShortName());
            indexDataVO.setDays(calcDays(sdf.format(new Date()), activity.getStartTime()));
        }
        else if(type ==2)
        {
            GroupRecruit groupRecruit = (GroupRecruit)object;
            indexDataVO.setId(-1L);
            indexDataVO.setType("GroupRecruit");
            indexDataVO.setCode(groupRecruit.getGroup().getGroupCode());
            indexDataVO.setObjectId(groupRecruit.getId());
            indexDataVO.setTitle(groupRecruit.getTitle());
            indexDataVO.setCreateTime(groupRecruit.getCreateTime());
            indexDataVO.setImg(groupRecruit.getImg());
            indexDataVO.setParticipants(groupRecruit.getApplys());
            indexDataVO.setBrowses(groupRecruit.getBrowses());
            indexDataVO.setOrgName(groupRecruit.getGroup().getShortName());
            indexDataVO.setDays(calcDays(sdf.format(new Date()), groupRecruit.getStopApplyTime()));
        }
        else if(type ==3)
        {
            ActivityRecruit activityRecruit = (ActivityRecruit)object;
            IndexData indexData = this.indexDataService.findByActivityRecruit(activityRecruit.getId());
            if(null != indexData)
                return IndexDataVO.buildVO(indexData);
        }
        return indexDataVO;
    }
    private long calcDays(String startDay,String endDay)
    {
        long days = DateUtil.countDay(startDay, endDay) + 1;
        return days;
    }
    @RequestMapping(value = "/search/{content}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> search(@PathVariable("content") String content)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            List<SearchResultVO> vos = new ArrayList<SearchResultVO>();
            //查询活动
            List<Activity> acts = this.activityService.findNameLike(content.trim());
            if (null != acts && acts.size() > 0)
                for (Activity activity : acts)
                    vos.add(SearchResultVO.buildActivity(activity));
            //查询社团
            List<Group> groups = this.groupService.findNameLike(content.trim(),10);
            if (null != groups && groups.size() > 0)
                for (Group group : groups)
                    vos.add(SearchResultVO.buildGroup(group));
            //查询话题
            List<SysTopic> topics = this.sysTopicService.findTitleLike(content.trim());
            if (null != topics && topics.size() > 0)
                for (SysTopic topic : topics)
                    vos.add(SearchResultVO.buildTopic(topic));
            //查询社团招募
            List<GroupRecruit> recruits = this.groupRecruitService.findTitleLike(content.trim());
            if (null != recruits && recruits.size() > 0)
                for (GroupRecruit groupRecruit : recruits)
                    vos.add(SearchResultVO.buildGroupRecruit(groupRecruit));
//            //查询活动招募
//            List<ActivityRecruit> activityRecruits = this.activityRecruitService.findTitleLike(content.trim());
//            if (null != activityRecruits && activityRecruits.size() > 0)
//                for (ActivityRecruit groupRecruit : activityRecruits)
//                    vos.add(SearchResultVO.buildActivityRecruit(groupRecruit));

            if (null != vos && vos.size() > 0)
            {
                sortClass sort = new sortClass();
                Collections.sort(vos, sort);
                Map<String,Object> resultMap = new HashMap<String, Object>();
                resultMap.put("list",vos);
                jsonResult.setData(resultMap);
            }
            else
                jsonResult.setData(new HashMap<String,Object>() );
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }
        return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
    }

    @RequestMapping(value = "/tag/{tag}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> searchByTag(@PathVariable("tag") String tag)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            List<SearchResultVO> vos = new ArrayList<SearchResultVO>();
            //查询活动
            List<Activity> acts = this.activityService.findTagsLike(tag.trim());
            if (null != acts && acts.size() > 0)
                for (Activity activity : acts)
                    vos.add(SearchResultVO.buildActivity(activity));
            //查询社团
            List<Group> groups = this.groupService.findServiceFieldLike(tag.trim(), 10);
            if (null != groups && groups.size() > 0)
                for (Group group : groups)
                    vos.add(SearchResultVO.buildGroup(group));
            //查询话题
            List<SysTopic> topics = this.sysTopicService.findTagsLike(tag.trim());
            if (null != topics && topics.size() > 0)
                for (SysTopic topic : topics)
                    vos.add(SearchResultVO.buildTopic(topic));

            //查询社团招募
            List<GroupRecruit> recruits = this.groupRecruitService.findByJobSkillSerivice(tag.trim());
            if (null != recruits && recruits.size() > 0)
                for (GroupRecruit groupRecruit : recruits)
                    vos.add(SearchResultVO.buildGroupRecruit(groupRecruit));
            //查询活动招募
            List<ActivityRecruit> activityRecruits = this.activityRecruitService.findByJobSkillSerivice(tag.trim());
            if (null != activityRecruits && activityRecruits.size() > 0)
                for (ActivityRecruit groupRecruit : activityRecruits)
                    vos.add(SearchResultVO.buildActivityRecruit(groupRecruit));

            if (null != vos && vos.size() > 0)
            {
                sortClass sort = new sortClass();
                Collections.sort(vos, sort);
                Map<String,Object> resultMap = new HashMap<String, Object>();
                resultMap.put("list", vos);
                jsonResult.setData(resultMap);
            }
            else
                jsonResult.setData(new HashMap<String,Object>() );
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }

        return new ResponseEntity<Object>(jsonResult, HttpStatus.OK);
    }

    @Resource
    private OrganizationService organizationService;

    @RequestMapping(value = "/test", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    @Login
    public ListDataResponseVo<OrgTestVo> testConfig()
    {
        List<OrgTestVo> orgTestVos = organizationService.findByContation("100002", "3403b0", "13800000001", "order by c.ORGID", 1, 10);

        return new ListDataResponseVo<>(1,"",orgTestVos);
    }

    public static void main(String[] args)
    {
        List<String> temp = new ArrayList<>();
        temp.add("12");
        temp.add("34");
        temp.add("56");
        System.out.println(temp.toString());
        temp.add(0,"00");
        System.out.println(temp.toString());
    }

    class sortClass implements Comparator
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        public int compare(Object arg0, Object arg1)
        {
            SearchResultVO v0 = (SearchResultVO) arg0;
            SearchResultVO v1 = (SearchResultVO) arg1;

            try
            {
                Date begin = sdf.parse(v0.getCreateTime());
                Date end = sdf.parse(v1.getCreateTime());
                if (begin.before(end))
                {
                    return 1;
                }
                else
                {
                    return -1;
                }

            } catch (ParseException e)
            {
                e.printStackTrace();
            }
            return 0;
        }
    }
}



